package com.hallowd.purcom;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;


public class CreateCommunity extends Activity {
    private static final String TAG = CreateCommunity.class.getSimpleName();

    Button mSaveButton;
    Button homeButton;
    EditText mDescription;
    EditText mCommunityName;
    RadioGroup mGroup1;
    RadioGroup mGroup2;
    RadioButton mTransient;
    RadioButton mPermanent;
    RadioButton mPublic;
    RadioButton mPrivate;
    Activity myActivity;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_community);

        myActivity = this;

        mDescription = (EditText) findViewById(R.id.description);
        mCommunityName = (EditText) findViewById(R.id.communityName);
        //mGroup1 = (RadioGroup) findViewById(R.id.radioG1);
        //mGroup2 = (RadioGroup) findViewById(R.id.radioG2);
        // radio button kısımlarını yapmadım. databasede de ilgili kolonlar yok sanırım. status ne?
        homeButton = (Button) findViewById(R.id.homeButton);
        homeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(myActivity, wellcomePageActivity.class);
                startActivity(intent);
            }
        });
            mSaveButton = (Button) findViewById(R.id.saveButton);
        mSaveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                (new CreateCommunityAsyncTask()).execute();
            }
        });
    }

    private class CreateCommunityAsyncTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params)  {
            String url = "http://titan.cmpe.boun.edu.tr:8089/purcom/mobile/community/new"; // /user/signup/"; Değişecek
            String communityName = mCommunityName.getText().toString();
            String description = mDescription.getText().toString();
            int status=0;
            Date enddate = null;
            int type = 0;
           // url = url + "?communityName=" + communityName + "&description=" + description;
            Log.d(TAG, url);

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost request = new HttpPost(url);
            request.addHeader("Content-Type","application/json");
            request.addHeader("Accept","application/json");

            Long userId = null;
            SharedPreferences pref = getApplicationContext().getSharedPreferences("purcomPref", MODE_PRIVATE);
            userId = pref.getLong("userID",-1L);


            try {
                JSONObject community = new JSONObject();
                //Map<String, Object> community = new TreeMap<String, Object>();
                community.put("name", communityName);
                community.put("description", description);
                community.put("status", status);
                community.put("enddate", enddate);
                community.put("type", type);
                JSONObject b = new JSONObject();
                b.put("community",community);
                b.put("userID",userId);

               // jsonObject.accumulate("userID",userID);
                //  jsonObject.accumulate("", selectedSkill);
                // 4. convert JSONObject to JSON to String


                String  json = b.toString();

                // ** Alternative way to convert Person object to JSON string usin Jackson Lib
                // ObjectMapper mapper = new ObjectMapper();
                // json = mapper.writeValueAsString(person);

                // 5. set json to StringEntity
                StringEntity se = new StringEntity(json);

                // 6. set httpPost Entity
                request.setEntity(se);

                HttpResponse response = httpclient.execute(request);
                if (response.getStatusLine().getStatusCode() == 200) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

                    StringBuilder builder = new StringBuilder();
                    for (String line = null; (line = reader.readLine()) != null; ) {
                        builder.append(line).append("\n");
                    }

                    Log.d(TAG, "Create Community " + builder.toString());
                    return builder.toString();
                }
                else
                    Log.d(TAG, "Create Community Failed");
            } catch (Exception e) {
                Log.d(TAG, e.toString());
                Log.d(TAG, e.getCause().toString());
                Log.d(TAG, "Connection problem occured");
            }

            return null;
        }

        protected void onPostExecute(String result) {
            AlertDialog.Builder builder = new AlertDialog.Builder(CreateCommunity.this);
            builder.setMessage("You successfully created community!")
                    .setTitle("CreateCommunity Result")
                    .setPositiveButton(android.R.string.ok, null);
            AlertDialog dialog = builder.create();
            dialog.show();
            Intent myintent = new Intent(myActivity,wellcomePageActivity.class);
            startActivity(myintent);
        }
    }
}
